package com.ruoyi.oa.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.oa.domain.OaFinanceTripApply;
import com.ruoyi.oa.domain.vo.OaFinanceTripApplyVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.oa.domain.bo.OaFinanceTravelBo;
import com.ruoyi.oa.domain.vo.OaFinanceTravelVo;
import com.ruoyi.oa.domain.OaFinanceTravel;
import com.ruoyi.oa.mapper.OaFinanceTravelMapper;
import com.ruoyi.oa.service.IOaFinanceTravelService;
import com.ruoyi.workflow.service.IProcessInstanceService;
import com.ruoyi.workflow.service.IUserService;
import com.ruoyi.workflow.utils.WorkFlowUtils;

import java.util.*;
import java.util.stream.Collectors;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.oa.domain.vo.OaProjectVo;

/**
 * 差旅费Service业务层处理
 *
 * @author wangxq
 * @date 2023-05-18
 */
@RequiredArgsConstructor
@Service
public class OaFinanceTravelServiceImpl implements IOaFinanceTravelService {

    private final OaFinanceTravelMapper baseMapper;

    private final IProcessInstanceService iProcessInstanceService;

    private final IUserService iUserService;
    /**
     * 查询差旅费
     */
    @Override
    public OaFinanceTravelVo queryById(String id){
        OaFinanceTravelVo vo= baseMapper.selectVoById(id);
        WorkFlowUtils.setStatusFileValue(vo,vo.getId());
        return vo;
    }

    /**
     * 查询差旅费列表
     */
    @Override
    public TableDataInfo<OaFinanceTravelVo> queryPageList(OaFinanceTravelBo bo, PageQuery pageQuery) {
        if (StringUtils.isNotBlank(bo.getCreateBy())){
            String userName = iUserService.getUserNameByNickName(bo.getCreateBy());
            if (StringUtils.isNotBlank(userName)){
                bo.setCreateBy(userName);
            }
        }
        if (CollectionUtil.isNotEmpty(bo.getSubmitTimeList())){
            bo.setSubmitStartDate(bo.getSubmitTimeList().get(0));
            bo.setSubmitEndDate(bo.getSubmitTimeList().get(1));
        }
        List<OaFinanceTravelVo> voList = baseMapper.queryByCondition(bo);
        // 添加流程信息
        if (CollectionUtil.isNotEmpty(voList)) {
            List<String> list = voList.stream().map(OaFinanceTravelVo::getId).collect(Collectors.toList());
            WorkFlowUtils.setStatusListFileValue(voList, list, "id");
        }
        // 筛选状态
        if (StringUtils.isNotBlank(bo.getStatus())) {
            List<OaFinanceTravelVo> temp = new ArrayList<>();
            for (OaFinanceTravelVo vo : voList) {
                if (vo.getActBusinessStatus().getStatus().equals(bo.getStatus())) {
                    temp.add(vo);
                }
            }
            voList = temp;
        }

        // 筛选提交时间
        if (CollectionUtil.isNotEmpty(bo.getSubmitTimeList())) {
            List<OaFinanceTravelVo> temp = new ArrayList<>();
            Date submitStartDate = bo.getSubmitStartDate();
            Date submitEndDate = bo.getSubmitEndDate();
            for (OaFinanceTravelVo vo : voList) {
                Date createTime = vo.getActBusinessStatus().getCreateTime();
                if (ObjectUtil.isNotEmpty(createTime) && createTime.after(submitStartDate) && createTime.before(submitEndDate)) {
                    temp.add(vo);
                }
            }
            voList = temp;
        }

        // 筛选提交人
        if (StringUtils.isNotEmpty(bo.getCreateBy())) {
            String[] split = bo.getCreateBy().split(",");
            List<String> list = Arrays.asList(split);
            List<OaFinanceTravelVo> temp = new ArrayList<>();
            for (OaFinanceTravelVo vo : voList) {
                if (ObjectUtil.isNotEmpty(vo.getActBusinessStatus().getCreateTime()) && list.indexOf(vo.getActBusinessStatus().getCreateBy())!=-1) {
                    temp.add(vo);
                }
            }
            voList = temp;
        }

        Page<OaFinanceTravelVo> result = new Page<>();
        result.setTotal(voList.size());

        int start = (pageQuery.getPageNum() - 1) * pageQuery.getPageSize();
        int end = Math.min(pageQuery.getPageNum() * pageQuery.getPageSize(), voList.size());
        voList = voList.subList(start, end);

        result.setRecords(voList);
        result.setCurrent(pageQuery.getPageNum());
        result.setSize(pageQuery.getPageSize());

        return TableDataInfo.build(result);
    }

    /**
     * 查询差旅费列表
     */
    @Override
    public List<OaFinanceTravelVo> queryList(OaFinanceTravelBo bo) {
        LambdaQueryWrapper<OaFinanceTravel> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<OaFinanceTravel> buildQueryWrapper(OaFinanceTravelBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<OaFinanceTravel> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), OaFinanceTravel::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getDept()), OaFinanceTravel::getDept, bo.getDept());
        lqw.eq(StringUtils.isNotBlank(bo.getCostType()), OaFinanceTravel::getCostType, bo.getCostType());
        lqw.eq(StringUtils.isNotBlank(bo.getNameBank()), OaFinanceTravel::getNameBank, bo.getNameBank());
        lqw.eq(StringUtils.isNotBlank(bo.getCardNumber()), OaFinanceTravel::getCardNumber, bo.getCardNumber());
        lqw.eq(bo.getReimbursementTotal() != null, OaFinanceTravel::getReimbursementTotal, bo.getReimbursementTotal());
        return lqw;
    }

    /**
     * 新增差旅费
     */
    @Override
    public OaFinanceTravelBo insertByBo(OaFinanceTravelBo bo) {
        LoginUser currentUser = LoginHelper.getLoginUser();
        bo.setDeptId(currentUser.getDeptId());
        bo.setUserId(currentUser.getUserId());
        OaFinanceTravel add = BeanUtil.toBean(bo, OaFinanceTravel.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return bo;
    }

    /**
     * 修改差旅费
     */
    @Override
    public OaFinanceTravel updateByBo(OaFinanceTravelBo bo) {
        OaFinanceTravel update = BeanUtil.toBean(bo, OaFinanceTravel.class);
        validEntityBeforeSave(update);
        int i =baseMapper.updateById(update);
        return update;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OaFinanceTravel entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除差旅费
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        for (String id : ids) {
            String processInstanceId = iProcessInstanceService.getProcessInstanceId(id);
            if (StringUtils.isNotBlank(processInstanceId)) {
                iProcessInstanceService.deleteRuntimeProcessAndHisInst(processInstanceId);
            }
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    /**
     * 获取没有采购流程的项目信息
     * @return
     */
    @Override
    public List<OaProjectVo> getProjectList() {
        return baseMapper.getProjectList();
    }


    /**
     * 通过项目名称查询差旅费申请
     * @param projectName
     * @return
     */
    @Override
    public OaFinanceTravelVo queryByProjectName(String projectName) {
        LambdaQueryWrapper<OaFinanceTravel> lqw = Wrappers.lambdaQuery();
        lqw.eq(OaFinanceTravel::getProjectName, projectName);
        OaFinanceTravelVo vo = baseMapper.selectVoOne(lqw);
        if (ObjectUtil.isEmpty(vo)){
            return null;
        }
        WorkFlowUtils.setStatusFileValue(vo,vo.getId());
        return vo;
    }
}
